<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/11/28
 * Time: 11:43
 */

namespace App\Common\Middleware\SysMiddleware;

use App\Extend\SysExtend\Middleware\MiddlewareInterface;
use EasySwoole\Http\Message\Status;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;

/**
 * 跨域中间件
 * Class CrossDomainMiddleware
 * @package App\Common\Middleware\SysMiddleware
 */
class CrossDomainMiddleware implements MiddlewareInterface
{

    /**
     * 控制方法执行前执行的方法
     * @param Request $request
     * @param Response $response
     * @return mixed
     */
    public function before(Request $request, Response $response)
    {
        $response->withHeader('Access-Control-Allow-Origin', '*');
        $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        $response->withHeader('Access-Control-Allow-Credentials', 'true');
        $response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        if ($request->getMethod() === 'OPTIONS') {
            $response->withStatus(Status::CODE_OK);
            return false;
        }
        return true;
    }

    /**
     * 控制方法执行后执行的方法
     * @param Request $request
     * @param Response $response
     * @return mixed
     */
    public function after(Request $request, Response $response)
    {
        // TODO: Implement after() method.
    }
}